package com.aabte.design2.behavioral.command;

import lombok.Data;

import java.util.Collection;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/5/3
 */
@Data
public class Application {
    private String clipboard;
    private Collection<Editor> editors;
    private Editor activeEditor;
    private CommandHistory history = new CommandHistory();

    Button copyButton = new Button();
    Button cutButton = new Button();
    Button pasteButton = new Button();
    Button undoButton = new Button();

    public static void main(String[] args) {
        Application application = new Application();
        application.createUI();

        application.activeEditor.setText("abcdefg");
        application.activeEditor.setSelection("abc");

        application.copyButton.onClick();
        application.cutButton.onClick();
        application.pasteButton.onClick();
        application.undoButton.onClick();

    }

    public void createUI() {

        activeEditor = new Editor();

        CopyCommand copyCommand = new CopyCommand(this, activeEditor);
        copyButton.setCommand(copyCommand);


        CutCommand cutCommand = new CutCommand(this, activeEditor);
        cutButton.setCommand(cutCommand);


        PasteCommand pasteCommand = new PasteCommand(this, activeEditor);
        pasteButton.setCommand(pasteCommand);


        UndoCommand undoCommand = new UndoCommand(this, activeEditor);
        undoButton.setCommand(undoCommand);

    }

    public void setClipboard(String clipboard) {
        this.clipboard = clipboard;
    }

    public String getClipboard() {
        return clipboard;
    }

    /**
     * 执行一个命令并检查它是否需要被添加到历史记录中
     */
    public void executeCommand(AbstractCommand command) {
        if (command.execute()) {
            history.push(command);
        }
    }

    /**
     * 从历史记录中取出最近的命令并运行其 undo（撤销）方法。请注意，你并
     * 不知晓该命令所属的类。但是我们不需要知晓，因为命令自己知道如何撤销
     * 其动作
     */
    public void undo() {
        AbstractCommand command = history.pop();
        if (null != command) {
            command.undo();
        }
    }
}
